package resource.manager.classes;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;

public class DatabaseManager {

   private Context context;
   private SQLiteDatabase db;
   private SQLiteStatement insertStmt;
   private String databaseName = "resources.db";
   private int databaseVersion = 1;
   private String tableName;
   private String insertCommand ;
 
   
    public String getTableName() {
	   return tableName;
	}
	
	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	public String getInsertCommand() {
		return insertCommand;
	}
	
	public void setInsertCommand(String insertCommand) {
		this.insertCommand = insertCommand;
		this.insertStmt = this.db.compileStatement(insertCommand);
	}

	
   public DatabaseManager(Context context) {
      this.context = context;
      OpenHelper openHelper = new OpenHelper(this.context);
      this.db = openHelper.getWritableDatabase();  
   }
   
   public SQLiteDatabase getDb() {
      return this.db;
   }

   public long insert(String name) {
      this.insertStmt.bindString(1, name);
      return this.insertStmt.executeInsert();
   }
   
   public void deleteAll() {
      this.db.delete(tableName, null, null);
   }

   public List<String> selectAll() {
      List<String> list = new ArrayList<String>();
      Cursor cursor = this.db.query(tableName, new String[] { "name" }, null, null, null, null, "name desc");
      if (cursor.moveToFirst()) {
         do {
            list.add(cursor.getString(0)); 
         } while (cursor.moveToNext());
      }
      if (cursor != null && !cursor.isClosed()) {
         cursor.close();
      }
      return list;
   }

   private class OpenHelper extends SQLiteOpenHelper {

      OpenHelper(Context context) {
         super(context, databaseName, null, databaseVersion);
      }

      @Override
      public void onCreate(SQLiteDatabase db) {
         db.execSQL("CREATE TABLE " + tableName + " (id INTEGER PRIMARY KEY, name TEXT)");
      }

      @Override
      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      }
   }
}